import { faker } from '@faker-js/faker';
import { verifyAccessToken } from '~/utils/jwt-utils';
import { unAuthorizedResponse, useResponseSuccess } from '~/utils/response';

function formatDate(date: Date): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function generateMockDataList(count: number) {
  const dataList = [];
  const accountants = ['张会计', '李会计', '王会计', '赵会计', '陈会计'];
  const supervisors = ['张主管', '李主管', '王主管', '赵主管', '陈主管'];
  const bookkeepers = ['张制单', '李制单', '王制单', '赵制单', '陈制单'];

  for (let i = 0; i < count; i++) {
    const customerCode = `C${String(i + 1).padStart(6, '0')}`;
    const dataItem: Record<string, any> = {
      id: (i + 1).toString(),
      customerCode,
      customerName: faker.company.name(),
      organizationName: `${faker.company.name()}有限公司`,
      status: faker.helpers.arrayElement([0, 1]),
      accountant: faker.helpers.arrayElement(accountants),
      supervisor: faker.helpers.arrayElement(supervisors),
      bookkeeper: faker.helpers.arrayElement(bookkeepers),
      createTime: formatDate(
        faker.date.between({ from: '2023-01-01', to: '2024-12-31' }),
      ),
      remark: faker.lorem.sentence(),
    };
    dataList.push(dataItem);
  }

  return dataList;
}

const mockData = generateMockDataList(50);

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return unAuthorizedResponse(event);
  }

  const query = getQuery(event);
  const page = Number(query.page) || 1;
  const pageSize = Number(query.pageSize) || 20;

  // 分页处理
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const listData = mockData.slice(startIndex, endIndex);

  return useResponseSuccess({
    list: listData,
    total: mockData.length,
    page,
    pageSize,
  });
});